import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 配置常量
const UPLOAD_PATH = process.env.UPLOAD_PATH || 'uploads/';
const MAX_FILE_SIZE = parseInt(process.env.MAX_FILE_SIZE) || 5 * 1024 * 1024; // 5MB
const ALLOWED_FILE_TYPES = (process.env.ALLOWED_FILE_TYPES || 'image/jpeg,image/png,image/gif,video/mp4').split(',');

// 确保上传目录存在 - 使用绝对路径
const uploadDir = path.isAbsolute(UPLOAD_PATH)
  ? UPLOAD_PATH
  : path.join(process.cwd(), UPLOAD_PATH);
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 创建子目录
const createSubDirectories = () => {
  const subDirs = ['pets', 'sightings', 'temp'];
  subDirs.forEach(dir => {
    const dirPath = path.join(uploadDir, dir);
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath, { recursive: true });
    }
  });
};

createSubDirectories();

/**
 * 生成唯一文件名
 * @param {string} originalName - 原始文件名
 * @returns {string} 唯一文件名
 */
function generateUniqueFilename(originalName) {
  const timestamp = Date.now();
  const randomString = Math.random().toString(36).substring(2, 15);
  const extension = path.extname(originalName);
  return `${timestamp}_${randomString}${extension}`;
}

/**
 * 文件过滤器
 * @param {Object} req - Express请求对象
 * @param {Object} file - 文件对象
 * @param {Function} cb - 回调函数
 */
function fileFilter(req, file, cb) {
  // 检查文件类型
  if (ALLOWED_FILE_TYPES.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error(`不支持的文件类型: ${file.mimetype}。支持的类型: ${ALLOWED_FILE_TYPES.join(', ')}`), false);
  }
}

/**
 * 存储配置
 */
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 根据上传类型决定存储目录
    let subDir = 'temp';
    
    if (req.uploadType) {
      subDir = req.uploadType;
    } else if (req.path.includes('pets')) {
      subDir = 'pets';
    } else if (req.path.includes('sightings')) {
      subDir = 'sightings';
    }
    
    const destPath = path.join(uploadDir, subDir);
    cb(null, destPath);
  },
  filename: function (req, file, cb) {
    const uniqueName = generateUniqueFilename(file.originalname);
    cb(null, uniqueName);
  }
});

/**
 * 基础上传配置
 */
const upload = multer({
  storage: storage,
  limits: {
    fileSize: MAX_FILE_SIZE,
    files: 5 // 最多5个文件
  },
  fileFilter: fileFilter
});

/**
 * 宠物照片上传中间件
 */
export const uploadPetPhoto = (req, res, next) => {
  req.uploadType = 'pets';
  upload.single('photo')(req, res, (err) => {
    if (err) {
      if (err instanceof multer.MulterError) {
        if (err.code === 'LIMIT_FILE_SIZE') {
          return res.status(400).json({
            success: false,
            message: `文件大小超过限制 (${MAX_FILE_SIZE / 1024 / 1024}MB)`,
            timestamp: new Date().toISOString()
          });
        } else if (err.code === 'LIMIT_FILE_COUNT') {
          return res.status(400).json({
            success: false,
            message: '文件数量超过限制',
            timestamp: new Date().toISOString()
          });
        }
      }
      
      return res.status(400).json({
        success: false,
        message: err.message || '文件上传失败',
        timestamp: new Date().toISOString()
      });
    }
    
    next();
  });
};

/**
 * 目击线索照片上传中间件
 */
export const uploadSightingPhoto = (req, res, next) => {
  req.uploadType = 'sightings';
  upload.single('photo')(req, res, (err) => {
    if (err) {
      if (err instanceof multer.MulterError) {
        if (err.code === 'LIMIT_FILE_SIZE') {
          return res.status(400).json({
            success: false,
            message: `文件大小超过限制 (${MAX_FILE_SIZE / 1024 / 1024}MB)`,
            timestamp: new Date().toISOString()
          });
        }
      }
      
      return res.status(400).json({
        success: false,
        message: err.message || '文件上传失败',
        timestamp: new Date().toISOString()
      });
    }
    
    next();
  });
};

/**
 * 多文件上传中间件
 */
export const uploadMultipleFiles = (maxCount = 5) => {
  return (req, res, next) => {
    upload.array('files', maxCount)(req, res, (err) => {
      if (err) {
        if (err instanceof multer.MulterError) {
          if (err.code === 'LIMIT_FILE_SIZE') {
            return res.status(400).json({
              success: false,
              message: `文件大小超过限制 (${MAX_FILE_SIZE / 1024 / 1024}MB)`,
              timestamp: new Date().toISOString()
            });
          } else if (err.code === 'LIMIT_FILE_COUNT') {
            return res.status(400).json({
              success: false,
              message: `文件数量超过限制 (最多${maxCount}个)`,
              timestamp: new Date().toISOString()
            });
          }
        }
        
        return res.status(400).json({
          success: false,
          message: err.message || '文件上传失败',
          timestamp: new Date().toISOString()
        });
      }
      
      next();
    });
  };
};

/**
 * 删除文件
 * @param {string} filePath - 文件路径
 * @returns {Promise<boolean>} 是否删除成功
 */
export async function deleteFile(filePath) {
  try {
    // 如果是相对路径，使用uploadDir作为基础路径
    let fullPath;
    if (path.isAbsolute(filePath)) {
      fullPath = filePath;
    } else {
      // 如果文件路径以uploads/开头，直接使用uploadDir的父目录
      if (filePath.startsWith('uploads/')) {
        fullPath = path.join(path.dirname(uploadDir), filePath);
      } else {
        fullPath = path.join(uploadDir, filePath);
      }
    }

    if (fs.existsSync(fullPath)) {
      fs.unlinkSync(fullPath);
      return true;
    }
    return false;
  } catch (error) {
    console.error('删除文件失败:', error);
    return false;
  }
}

/**
 * 获取文件URL
 * @param {string} filename - 文件名
 * @param {string} subDir - 子目录
 * @returns {string} 文件URL
 */
export function getFileUrl(filename, subDir = 'temp') {
  if (!filename) return null;
  
  // 如果已经是完整URL，直接返回
  if (filename.startsWith('http')) {
    return filename;
  }
  
  // 如果已经包含uploads路径，直接返回
  if (filename.startsWith('uploads/')) {
    return `/${filename}`;
  }
  
  return `/uploads/${subDir}/${filename}`;
}

/**
 * 验证文件是否存在
 * @param {string} filePath - 文件路径
 * @returns {boolean} 文件是否存在
 */
export function fileExists(filePath) {
  try {
    const fullPath = path.join(process.cwd(), filePath);
    return fs.existsSync(fullPath);
  } catch (error) {
    return false;
  }
}

/**
 * 清理临时文件（删除超过24小时的临时文件）
 */
export function cleanupTempFiles() {
  const tempDir = path.join(uploadDir, 'temp');
  const now = Date.now();
  const maxAge = 24 * 60 * 60 * 1000; // 24小时

  try {
    if (fs.existsSync(tempDir)) {
      const files = fs.readdirSync(tempDir);
      
      files.forEach(file => {
        const filePath = path.join(tempDir, file);
        const stats = fs.statSync(filePath);
        
        if (now - stats.mtime.getTime() > maxAge) {
          fs.unlinkSync(filePath);
          console.log(`清理临时文件: ${file}`);
        }
      });
    }
  } catch (error) {
    console.error('清理临时文件失败:', error);
  }
}

// 定期清理临时文件（每小时执行一次）
setInterval(cleanupTempFiles, 60 * 60 * 1000);
